import * as API from '@/services';
import React, {ReactElement} from "react";
import {Tag} from "antd";

/**
 * 获取当前登录用户的认证token
 * 如果用户未登录返回null
 */
const authInfoKey = '_auth_info_';


export function getAuthToken(): string | null {
  const authInfo = getAuthInfo();
  if (authInfo) {
    return authInfo.token;
  }
  return null;
}

/**
 * 是否超级管理员
 * @param authInfo
 */
export function isSuperAdmin(authInfo: API.AuthInfo | undefined | null): boolean {
  if (authInfo?.principal?.userId == "1") {
    return true;
  }
  return hasAuthority(authInfo?.authorities || [], "ROLE_SUPER_ADMIN");
}

export function getAuthInfo(): API.AuthInfo | null {
  const authInfoStr = localStorage.getItem(authInfoKey);
  if (authInfoStr) {
    return JSON.parse(authInfoStr);
  }
  return null;
}

export function setAuthInfo(authInfo: API.AuthInfo): void {
  localStorage.setItem(authInfoKey, JSON.stringify(authInfo));
}

export function clearAuthInfo(): void {
  localStorage.removeItem(authInfoKey);
}

export function hasAuthority(userAuthorities: string[], authority: string): boolean {
  return hasAnyAuthority(userAuthorities, [authority])
}

//权限判断方法
export function hasAnyAuthority(userAuthorities: string[], authorities: string[]): boolean {
  return userAuthorities.length > 0 && !!userAuthorities.find(d => authorities.includes(d))
}

export const getIdentityTypeDesc = (identityType: string) => {
  let desc: ReactElement = <Tag color="blue">{identityType}</Tag>;
  switch (identityType) {
    case 'PWD_LOGIN_NAME':
      desc = <Tag color="blue">用户名类型</Tag>;
      break;
    case 'PWD_EMAIL':
      desc = <Tag color="geekblue">邮箱类型</Tag>;
      break;
    case 'PWD_MOBILE':
      desc = <Tag color="purple">手机号类型</Tag>;
      break;
    case 'WECHAT_MP':
      desc = <Tag color="green">微信公众号</Tag>;
      break;
    case 'WECHAT_MINIAPP':
      desc = <Tag color="green">微信小程序</Tag>;
      break;
    case 'WECHAT_OPEN':
      desc = <Tag color="green">微信PC</Tag>;
      break;
    default:
      break;
  }

  return desc;
};
